const { app, BrowserWindow, protocol } = require('electron')
const path = require('path')
const log = require('electron-log')

// 配置日志
log.transports.file.level = 'error'
log.transports.console.level = false

// 启用远程模块
require('@electron/remote/main').initialize()

// 注册文件协议
function registerFileProtocol() {
  protocol.registerFileProtocol('safe-file', (request, callback) => {
    const url = request.url.replace('safe-file://', '')
    try {
      const decodedPath = decodeURIComponent(url)
      return callback(decodedPath)
    } catch (error) {
      log.error('文件协议处理错误:', error)
    }
  })
}

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 1280,
    height: 720,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false,
      allowRunningInsecureContent: false,
      devTools: process.env.NODE_ENV === 'development'
    }
  })

  require('@electron/remote/main').enable(mainWindow.webContents)

  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173')
    mainWindow.webContents.openDevTools()
  } else {
    const indexPath = path.join(__dirname, '../../dist/index.html')
    mainWindow.loadFile(indexPath).catch(err => {
      log.error('加载index.html失败:', err)
    })
  }

  // 监听渲染进程错误
  mainWindow.webContents.on('crashed', (event) => {
    log.error('渲染进程崩溃:', event)
  })

  mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    log.error('页面加载失败:', { errorCode, errorDescription })
  })
}

app.whenReady().then(() => {
  registerFileProtocol()
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// 捕获未处理的异常
process.on('uncaughtException', (error) => {
  log.error('未捕获的异常:', error)
})

process.on('unhandledRejection', (reason) => {
  log.error('未处理的Promise拒绝:', reason)
}) 